package info.batcloud.fanli.core.service.impl;

import com.taobao.api.ApiException;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import info.batcloud.fanli.core.constants.MessageKeyConstants;
import info.batcloud.fanli.core.context.StaticContext;
import info.batcloud.fanli.core.helper.SvgHelper;
import info.batcloud.fanli.core.service.*;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TaobaoNewerServiceImpl implements TaobaoNewerService {

    private Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);

    @Inject
    private UserService userService;

    @Inject
    private
    UrlMappingService urlMappingService;

    @Inject
    private TbkService tbkService;

    @Inject
    private ShortUrlService shortUrlService;

    @PostConstruct
    public void init() {
        configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), ""));
    }

    @Override
    public ShareInfo findUserShareInfo(long userId) {
        String pid = userService.getTaobaoPidByUserId(userId);
        return findShareInfoByPid(pid);
    }

    @Override
    public ShareInfo findShareInfoByPid(String pid) {
        String shareUrl = urlMappingService.getTaobaoNewerShareUrl(pid);
        ShareInfo shareInfo = new ShareInfo();
        shareInfo.setUrl(shareUrl);
        shareInfo.setPid(pid);
        String shortUrl = shortUrlService.generate(shareUrl);
        String lxUrl = "https://mos.m.taobao.com/activity_newer?from=pub&pid=" + pid;
        shareInfo.setShortUrl(shortUrl);
        List<String> shareTexts = new ArrayList<>();
        shareTexts.add(StaticContext.messageSource.getMessage(MessageKeyConstants.TAOBAO_NEWER_SHARE_TEXT, new Object[]{shortUrl}, null, null));
        try {
            String kl = tbkService.transformToToken("淘宝拉新活动", lxUrl);
            if (StringUtils.isNotBlank(kl)) {
                shareTexts.add(StaticContext.messageSource.getMessage(MessageKeyConstants.TAOBAO_NEWER_SHARE_TEXT_KL, new Object[]{kl}, null, null));
                shareInfo.setKl(kl);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        shareInfo.setText(String.join("\n", shareTexts));
        return shareInfo;
    }

    @Override
    public String genSharePicSvgXml(String url) {
        Template template = null;
        try {
            template = configuration.getTemplate("tblx.svg.ftlh");
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringWriter writer = new StringWriter();
        try {
            Map<String, Object> model = new HashMap<>();
            model.put("url", URLEncoder.encode(url, "utf8"));
            template.process(model, writer);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer.toString();
    }

    @Override
    public void genSharePic(String url, OutputStream os) {
        String svg = this.genSharePicSvgXml(url);
        try {
            SvgHelper.convertToJpg(svg, os, 750f, 1122f);
        } catch (TranscoderException e) {
            e.printStackTrace();
        }
    }
}
